# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur = ListNode(0)
        ret = cur

        flag = 0
        while (l1 is not None or l2 is not None):
            
            if l1 and l2:
                ans = l1.val + l2.val + flag
                l1 = l1.next
                l2 = l2.next
            elif l1:
                ans = l1.val + flag
                l1 = l1.next
            elif l2:
                ans = l2.val + flag
                l2 = l2.next

            flag = int(ans/10)
            ans = ans % 10
            
            cur.next = ListNode(ans)
            cur = cur.next

        if flag > 0:
            cur.next = ListNode(flag)

        return ret.next

# l1 = ListNode(2)
# l1.next = ListNode(4)
# l1.next.next = ListNode(3)
# l2 = ListNode(5)
# l2.next = ListNode(6)
# l2.next.next = ListNode(4)

# solution = Solution()
# res = solution.addTwoNumbers(l1, l2)
# print(res.val, res.next.val, res.next.next.val)